import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { cancelAll } from '@/utils/request'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
// 白名单
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (store.state.user.token) {
    // 登录情况下
    if (to.path === '/login') {
      next('/')
    } else {
      // 页面刷新动态添加的路由为什么不会重置
      if (!store.state.user.userInfo.username) {
        // 调用获取用户信息接口
        await store.dispatch('user/asyncGetUserBaseInfo')
        next(to.fullPath) // 相当于多做一次跳转 to.path带参数重定向没铺好的404页面
      } else {
        next()
      }
    }
  } else {
    // 没有登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 要去有权限页面必定有fullpath
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  cancelAll() // 路由跳转取消所有之前请求
  NProgress.done()
})
